extends CharacterBody3D

@export var main_animation_player: AnimationPlayer
@export var moving_speed := 5.0
@export var run_acc_ratio := 2.0
@export var acceleration := 4.0
@export var stopping_speed := 1.0

@onready var skin: CharacterSkin = $CharacterSkin

const JUMP_VELOCITY = 4.5

var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")
var is_attacking: bool = false
var _acceleration: float
var _moving_speed: float

func _ready() -> void:
	_moving_speed = moving_speed
	_acceleration = acceleration

func _physics_process(delta):
	var move_direction = get_movement_direction()

	var y_velocity := velocity.y
	velocity = velocity.lerp(move_direction * _moving_speed, _acceleration * delta)
	if move_direction.length() == 0 and velocity.length() < stopping_speed:
		velocity = Vector3.ZERO
	# if is_attacking:
	# 	velocity = Vector3.ZERO
	velocity.y = y_velocity

	if not is_on_floor():
		velocity.y -= gravity * delta

	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = JUMP_VELOCITY
		skin.jump()
	elif not is_on_floor() and velocity.y < 0.1:
		skin.fall()
	elif is_on_floor():
		var xz_velocity := Vector3(velocity.x, 0, velocity.z)
		if xz_velocity.length() > 0.1:
			skin.moving = true
			skin.moving_speed = inverse_lerp(0.0, moving_speed * run_acc_ratio, xz_velocity.length())
			print(skin.moving_speed)
		else:
			skin.moving = false

	move_and_slide()

func get_movement_direction() -> Vector3:
	# if is_attacking:
	# 	return Vector3.ZERO
	var input_dir = Input.get_vector("move_right", "move_left", "move_back", "move_forward")
	return (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()

func _unhandled_input(event: InputEvent) -> void:
	if event.is_action("run"):
		if event.is_action_pressed("run"):
			_moving_speed = moving_speed * run_acc_ratio
		else:
			_moving_speed = moving_speed
	
	if event.is_action("attack"):
		if event.is_action_pressed("attack") and not is_attacking:
			is_attacking = true
			skin.attack()
		else:
			is_attacking = false
